package com.qf.mybatisplus.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ImgToByteUtils {
    private final static Logger logger = LoggerFactory.getLogger(ImgToByteUtils.class);
    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();

    public static void main(String[] args) {
        String s = Base64Util.imageToBase64("D:\\moko\\moke\\nginx\\nginx-1.15.0\\html\\MOKO-IMG\\photo\\11111111-20190717172751388.jpg");
        byte[] bytes = base64StringToImageBinary(s);
        byte2image(bytes,"D:\\bb.jpg");
        System.out.println(111);
    }

    //byte数组到图片
    public static void byte2image(byte[] data,String path){
        if(data.length<3||path.equals("")) return;
        try{
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            logger.info("Make Picture success,Please find image in " + path);
        } catch(Exception ex) {
          logger.error("Exception :"+ex);
            ex.printStackTrace();
        }
    }
    /**
     * 将图片base64转换为二进制
     *
     * @param base64String；
     */
    public static byte[] base64StringToImageBinary(String base64String) {
        if(StringUtils.isSpace(base64String)){
            return null;
        }
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //经测试转换的图片是格式这里就什么格式，否则会失真
            ImageIO.write(bi1, "jpg", baos);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将图片转换成二进制
     *
     * @return String;
     */
   public static String getImageBinary(String path) {
        File f = new File(path);

        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);  //经测试转换的图片是格式这里就什么格式，否则会失真
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
